<template>
  <div class="student-dashboard">
    <!-- 欢迎横幅 - 保持原有样式 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <h1>清心内省，找回真我</h1>
        <p>静下心来，放松身心，感受内心的平静与安宁</p>
        <p>敞开心扉，倾听自己，释放压力，享受生命的美好旅程</p>
        <el-button type="primary" size="large" @click="router.push('/counseling/stuappointment')">
          开始咨询
        </el-button>
      </div>
    </div>

    <!-- 主要内容区 -->
    <el-row :gutter="20" class="dashboard-content">
      <!-- 左侧区域 -->
      <el-col :span="16">
        <!-- 最新公告 -->
        <el-card class="dashboard-card notice-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><Bell /></el-icon>
                最新公告
              </h3>
              <el-button text @click="handleViewAllNotices">查看全部</el-button>
            </div>
          </template>
          <div class="notice-list">
            <div v-for="notice in noticeList" :key="notice.id" class="notice-item" @click="handleViewNotice(notice.id)">
              <div class="notice-title">
                <el-tag v-if="notice.isImportant" type="danger" effect="dark" size="small">重要</el-tag>
                <span>{{ notice.title }}</span>
              </div>
              <span class="notice-time">{{ formatDateTime(notice.createTime) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 心理知识 -->
        <el-card class="dashboard-card knowledge-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><Reading /></el-icon>
                心理知识
              </h3>
              <el-button text @click="handleViewAllKnowledge">查看全部</el-button>
            </div>
          </template>
          <el-row :gutter="20" class="knowledge-grid">
            <el-col v-for="article in knowledgeList.slice(0, 2)" :key="article.id" :span="12">
              <div class="knowledge-card-item" @click="handleViewArticle(article.id)">
                <el-image 
                  :src="article.coverUrl || defaultCover" 
                  fit="cover" 
                  class="knowledge-image"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="knowledge-info">
                  <h4>{{ article.title }}</h4>
                  <p>{{ article.description }}</p>
                  <div class="knowledge-meta">
                    <span>
                      <el-icon><Clock /></el-icon>
                      {{ formatDateTime(article.createTime) }}
                    </span>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 右侧区域 -->
      <el-col :span="8">
        <!-- 我的预约 -->
        <el-card class="dashboard-card appointment-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><Calendar /></el-icon>
                近期预约
              </h3>
              <el-button text @click="handleViewAllAppointments">查看全部</el-button>
            </div>
          </template>
          <div v-if="appointmentList.length" class="appointment-list">
            <div v-for="apt in appointmentList" :key="apt.id" class="apt-item">
              <div class="apt-time">
                <div class="date">{{ formatDate(apt.appointmentTime) }}</div>
                <div class="time">{{ formatTime(apt.appointmentTime) }}</div>
              </div>
              <div class="apt-info">
                <div class="counselor">{{ apt.counselorName }}</div>
                <el-tag :type="getStatusType(apt.status)" size="small">
                  {{ getStatusText(apt.status) }}
                </el-tag>
              </div>
            </div>
          </div>
          <el-empty v-else class="empty-block" description="暂无预约" />
        </el-card>

        <!-- 快速开始测试 -->
        <el-card class="dashboard-card quick-test-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><DocumentChecked /></el-icon>
                快速开始测试
              </h3>
            </div>
          </template>
          <div class="quick-test-content">
            <div class="test-intro">
              <p>心理测试可以帮助你：</p>
              <ul>
                <li>了解自己的性格特点</li>
                <li>评估当前心理状态</li>
                <li>发现潜在的心理困扰</li>
                <li>获得专业的建议指导</li>
              </ul>
            </div>
            <el-button 
              type="primary" 
              class="start-test-btn"
              @click="router.push('test/test-list')"
            >
              开始测试
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { 
  Calendar,
  Clock,
  Bell,
  Reading,
  Picture,
  DocumentChecked
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { getArticleList } from '@/api/article'
import { getAppointmentList } from '@/api/counseling'

// 定义接口
interface Notice {
  id: number
  title: string
  isImportant: boolean
  createTime: string
}

interface Article {
  id: number
  title: string
  description: string
  summary?: string
  coverUrl: string
  viewCount: number
  createTime: string
}

interface Appointment {
  id: number
  appointmentTime: string
  status: string
  counselorName: string
}

interface Mood {
  label: string
  value: string
  icon: string
}

const router = useRouter()
const store = useStore()
const userId = computed(() => store.state.user.id)
const defaultCover = '/images/default-article-cover.png'

// 使用定义的接口类型
const noticeList = ref<Notice[]>([])
const knowledgeList = ref<Article[]>([])
const appointmentList = ref<Appointment[]>([])

// 加载公告列表
const loadNotices = async () => {
  try {
    const { data } = await getArticleList({
      pageNum: 1,
      pageSize: 5,
      category: 'NOTICE',
      status: '1'
    })
    if (data && data.records) {
      noticeList.value = data.records
      console.log('Loaded notices:', data.records)
    }
  } catch (error) {
    console.error('加载公告失败:', error)
  }
}

// 加载心理知识
const loadKnowledge = async () => {
  try {
    const { data } = await getArticleList({
      pageNum: 1,
      pageSize: 4,
      category: 'KNOWLEDGE',
      status: '1'
    })
    if (data && data.records) {
      knowledgeList.value = data.records
      console.log('Loaded knowledge:', data.records)
    }
  } catch (error) {
    console.error('加载心理知识失败:', error)
  }
}

// 加载预约列表
const loadAppointments = async () => {
  try {
    const { data } = await getAppointmentList({
      pageNum: 1,
      pageSize: 5,
      status: '',
      counselorName: '',
      studentId: store.state.user.id
    })
    if (data && data.records) {
      appointmentList.value = data.records
    }
  } catch (error) {
    console.error('加载预约列表失败:', error)
  }
}

// 格式化方法
const formatDateTime = (time: string): string => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const formatDate = (time: string): string => {
  return dayjs(time).format('YYYY-MM-DD')
}

const formatTime = (time: string): string => {
  return dayjs(time).format('HH:mm')
}

// 状态相关方法
const getStatusType = (status: string): string => {
  const map: Record<string, string> = {
    'PENDING': 'warning',
    'CONFIRMED': 'success',
    'CANCELLED': 'info',
    'COMPLETED': 'success'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string): string => {
  const map: Record<string, string> = {
    'PENDING': '待确认',
    'CONFIRMED': '已确认',
    'CANCELLED': '已取消',
    'COMPLETED': '已完成'
  }
  return map[status] || status
}

// 事件处理方法
const handleViewAllNotices = () => {
  router.push('/notice/articlelist')
}

const handleViewAllKnowledge = () => {
  router.push('/notice/articlelist')
}

const handleViewArticle = (id: number) => {
  router.push(`/notice/detail/${id}`)
}

const handleViewAllAppointments = () => {
  router.push('counseling/appointment')
}

const handleViewNotice = (id: number) => {
  router.push(`/notice/detail/${id}`)
}

onMounted(() => {
  console.log('组件挂载，开始加载数据')
  console.log('当前用户ID:', userId.value)
  loadNotices()
  loadKnowledge()
  loadAppointments()
})
</script>

<style lang="scss" scoped>
.student-dashboard {
  .welcome-banner {
    height: 240px;
    background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
    border-radius: 8px;
    margin-bottom: 20px;
    padding: 40px;
    color: white;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(45deg, rgba(255,255,255,0.1) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.1) 50%, rgba(255,255,255,0.1) 75%, transparent 75%, transparent);
      background-size: 4px 4px;
      opacity: 0.2;
    }

    .banner-content {
      position: relative;
      z-index: 1;

      h1 {
        font-size: 32px;
        margin: 0 0 16px;
        font-weight: 600;
      }

      p {
        font-size: 16px;
        margin: 8px 0;
        opacity: 0.9;
      }

      .el-button {
        margin-top: 24px;
        padding: 12px 24px;
        font-size: 16px;
      }
    }
  }

  .dashboard-content {
    .dashboard-card {
      margin-bottom: 20px;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 12px;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 8px;
          color: #303133;

          .el-icon {
            font-size: 18px;
            color: var(--el-color-primary);
          }
        }
      }
    }

    .notice-card {
      .notice-list {
        height: 150px;
        overflow-y: auto;
      }
      
      .notice-item {
        padding: 12px 16px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }

        &:hover {
          background-color: #f5f7fa;
        }

        .notice-title {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;

          span {
            font-size: 14px;
            color: #303133;
          }
        }

        .notice-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .knowledge-card {
      .knowledge-card-item {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.3s;
        margin-bottom: 12px;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);

        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 4px 16px rgba(0,0,0,0.1);
        }

        .knowledge-image {
          width: 100%;
          height: 120px;
          object-fit: cover;
        }

        .knowledge-info {
          padding: 12px;

          h4 {
            margin: 0 0 8px;
            font-size: 16px;
            font-weight: 600;
            color: #303133;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          p {
            margin: 0 0 12px;
            color: #606266;
            font-size: 14px;
            line-height: 1.6;
            height: 40px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            display: flex;
            line-clamp: 2;
            box-orient: vertical;
            text-overflow: ellipsis;
          }

          .knowledge-meta {
            display: flex;
            justify-content: space-between;
            color: #909399;
            font-size: 12px;

            span {
              display: flex;
              align-items: center;
              gap: 4px;
            }
          }
        }
      }
    }

    .appointment-card {
      height: 273px;
      overflow: hidden;
      
      .appointment-list {
        max-height: 150px;
        overflow-y: auto;
        
        &::-webkit-scrollbar {
          width: 6px;
        }
        
        &::-webkit-scrollbar-thumb {
          background: #dcdfe6;
          border-radius: 3px;
        }
        
        &::-webkit-scrollbar-track {
          background: #f5f7fa;
        }
      }
      
      .apt-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        .apt-time {
          .date {
            font-size: 14px;
            color: #303133;
            font-weight: 500;
            margin-bottom: 4px;
          }

          .time {
            font-size: 12px;
            color: #909399;
          }
        }

        .apt-info {
          text-align: right;

          .counselor {
            font-size: 14px;
            color: #303133;
            margin-bottom: 4px;
          }
        }
      }
    }

    .empty-block {
      height: 150px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 0;
      
      :deep(.el-empty__image) {
        width: 80px;
        height: 80px;
      }
      
      :deep(.el-empty__description) {
        margin-top: 10px;
      }
    }

    .quick-test-card {
      height: calc(100% - 312px);
      margin-bottom: 0;

      .quick-test-content {
        padding: 20px;
        
        .test-intro {
          margin-bottom: 20px;
          
          p {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
            margin-bottom: 12px;
          }
          
          ul {
            padding-left: 20px;
            
            li {
              color: #606266;
              line-height: 1.8;
              margin-bottom: 6px;
              
              &:last-child {
                margin-bottom: 0;
              }
            }
          }
        }
        
        .start-test-btn {
          width: 100%;
          height: 40px;
          font-size: 16px;
        }
      }
    }
  }
}

.knowledge-card-item {
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 120px;
    background: #f5f7fa;
    color: #909399;
    font-size: 30px;
  }
  
  .knowledge-image {
    width: 100%;
    height: 120px;
    border-radius: 4px 4px 0 0;
    overflow: hidden;
  }
}

.notice-list::-webkit-scrollbar {
  width: 6px;
}

.notice-list::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.notice-list::-webkit-scrollbar-track {
  background: #f5f7fa;
}
</style>